function calculateChecksum(data) {
    let sum = 0;
    sum += data.DataType;
    sum += data.Length;
    for (let i = 0; i < data.Data.length; i++) {
        sum += data.Data[i];
    }
    sum = sum & 0xFF;
    let result = sum ^ 0xFF
    return result
}
// buffer转16进制
const ab2hex = (buffer) => {
    const res = new Uint8Array(buffer)
    const auth = calculateChecksum({
        DataType: res[1],
        Length: res[2],
        Data: res.slice(3, -1)
    })
    console.log(auth, '校验结果10进制---------------------')
    console.log(res[res.length - 1], '收到的数据最后一项')
    var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (bit) {
        return ("00" + bit.toString(16)).slice(-2);
    });
    console.log(hexArr, '收到的原始数据-----')
    if (res[0] == 67) {
        wx.showModal({
            title: '提示',
            content: '升级失败,请重新前往升级',
            complete: (res) => {
                if (res.cancel) {}
                if (res.confirm) {}
            }
        })
        return
    }
    if (auth == res[res.length - 1]) {
        console.log('校验通过')
        // var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (bit) {
        //     return ("00" + bit.toString(16)).slice(-2);
        // });
        return hexArr.join("");
    } else {
        // wx.showToast({
        //     title: '校验不通过',
        //     icon: 'error'
        // })
        console.log('校验不通过')
        return false
    }
}
// 16进制转字符串
const hexToStr = (hex) => {
    var str = '';
    for (var i = 0; i < hex.length - 1; i += 2) {
        var charCode = parseInt(hex.substr(i, 2), 16); // 将两位十六进制转换为十进制
        if (!isNaN(charCode)) {
            str += String.fromCharCode(charCode); // 根据十进制编码获取相应的字符并追加到结果字符串上
        } else {
            break; // 如果遇到非法的十六进制字符则停止转换
        }
    }
    return str;
}

//  校验和 data：16进制数据
const checkSumByData = (data) => {
    if (!data) return ''
    let total = 0;
    for (let i = 0; i < data.length; i += 2) {
        let str = data.substr(i, 2);
        total += parseInt(str, 16);
    }
    let hex = total.toString(16);
    // 判断校验位的长度，补0
    if (hex.length < 2) hex = `0${hex}`;
    return hex;
}


// 加密
const Encrypt = require('./jsencrypt');
import {
    PulicKey
} from './config'
let cryptFirst = new Encrypt.JSEncrypt();
cryptFirst.setPublicKey(PulicKey);
const passwordJsencrypt = (str) => {
    return cryptFirst.encrypt(str)
}


module.exports = {
    ab2hex,
    hexToStr,
    checkSumByData,
    passwordJsencrypt
}